
package com.itheima.controller.backend.security;

import com.itheima.mapper.PermissionMapper;
import com.itheima.mapper.UserMapper;
import com.itheima.pojo.MyUserDetails;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;


import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class SpringSecurityUserService implements UserDetailsService {
    //查找服务，实现查询数据库
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PermissionMapper permissionMapper;

    //根据用户名查询数据库中用户信息
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        // 从数据库中查询用户
        User user = userMapper.findByUsername(username);

        if (user == null) {
            throw new UsernameNotFoundException("用户名或密码错误");
        }

        MyUserDetails userDetails = new MyUserDetails();

        userDetails.setUsername(user.getUsername());
        userDetails.setPassword(user.getPassword());

        // 查询用户的角色
        List<Role> roles = userMapper.findRolesByUserId(user.getId());
        // 把角色转换成数组
        String[] roleCodes = roles.stream()
                .map(Role::getKeyword)
                .collect(Collectors.toList())
                .toArray(new String[0]);
        List<GrantedAuthority> authorityList = AuthorityUtils.createAuthorityList(roleCodes);

        // 设置用户的权限
        userDetails.setAuthorities(authorityList);

        return userDetails;

    }
}

